import { listenRequestQueueFile } from "./listenRequestQueue"
import { v4 } from 'uuid'
import { join } from "path"
import { registeOnDestoryHook } from '@core/types'
import { expressFactory } from './expressFactory'
import { homedir } from 'os'
import { ensureDir } from "fs-extra"
import { readJson, saveJson } from "./utils"
export async function node(root: string, name: string, hasServer: boolean = false, index: number = 0) {
    const home = homedir()
    registeOnDestoryHook()
    const jsonFile = `${index || process.env.INDEX || 0}.json`
    await ensureDir(join(home, 'sker', name))
    const configPath = join(home, 'sker', name, jsonFile)
    const config = await readJson(configPath)
    const uuid = config.uuid || v4()
    process.env.CLIENT_ID = uuid;
    await saveJson(configPath, { uuid })
    const closer1 = await listenRequestQueueFile(uuid, name, join(root, 'dist'))
    let closer2: Function;
    if (hasServer) {
        const app = await expressFactory(uuid, false)
        closer2 = await app.listen()
        console.info(`Server started on port ${process.env.HOST} ${process.env.PORT || 3000}`)
    }
    process.on('exit', async () => {
        await closer1()
        if (closer2) await closer2()
    })
    return uuid;
}
